import { Directive, ElementRef, HostListener } from '@angular/core';
//定义指令
const ClickingBackColor = '#eee';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[btnClickStyle]'//设置选择器
})
export class BtnClickDirective {
  private el: HTMLElement; //取得html对象
  private timer: any; //定义定时器
  private animating: boolean; //动画开关 默认false
  constructor(el: ElementRef) {
    this.el = el.nativeElement; //得到指令对象的dom
    this.el.style.transition = 'background-color .2s ease-out'; //设置动画时长
  }
  @HostListener('click') //监听指令dom对象的click事件
  doClick() {
    // tslint:disable-next-line:curly
    if (this.animating) return; //判断动画是否进行中
    this.animating = true;
    this.el.prevBackColor = this.el.style.backgroundColor; //记录初始颜色
    this.el.style.backgroundColor = ClickingBackColor;//修改颜色
    clearTimeout(this.timer); //定时器清除
    this.timer = setTimeout(() => {
      this.el.style.backgroundColor = this.el.prevBackColor || ''; //200毫秒后颜色设置为初始值
      this.animating = false;
    }, 200);
  }
}
//定义接口对象
interface HTMLElement {
  prevBackColor: string;
  style: any;
}
